package com.guoguo.listener;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.StaticResource;
import com.guoguo.entity.Purview;
import com.guoguo.entity.Recharge;
import com.guoguo.service.IPurviewService;
import com.guoguo.service.IRechargeService;
import com.guoguo.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统初始化
 * Created by Administrator on 2017/8/18 0018.
 */
public class SysInitConfig implements ApplicationListener<ContextRefreshedEvent> {
    private Logger log = LoggerFactory.getLogger(SysInitConfig.class);

    @Resource
    private IPurviewService iPurviewService;


    @Resource
    private IRechargeService iRechargeService;

    private RedisUtils redisUtils = RedisUtils.getInstance();


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
        initData();
    }

    /**
     * 系统初始化
     */
    private void initData() {
        log.info("===============>>>>    系统初始化开始.......");
        initPurview();
        initRecharge();

        log.info("===============>>>>    系统初始化结束.......");
    }

    /**
     * 权限初始化
     */
    private void initPurview() {
        log.info("===============>>>>    权限信息初始化开始.......");
        List<Purview> purviews = iPurviewService.getPurviewList(true);
        for (Purview purview : purviews) {
            redisUtils.hset(StaticResource.SYS_INIT_PURVIEW_KEY, purview.getUrl(), purview.getPermission());
        }
        log.info("===============>>>>    权限信息初始化结束.......");
    }

    private void initRecharge() {
        log.info("===============>>>>    支付信息初始化开始.......");
        List<Recharge> rechargeList = iRechargeService.getRechargeList();
        for (Recharge recharge : rechargeList) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(recharge);
            redisUtils.hset(StaticResource.SYS_INIT_RECHARGE_KEY, recharge.getRechId(), jsonObject.toJSONString());
        }
        log.info("===============>>>>    支付信息初始化结束.......");
    }
}
